﻿using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.Unity;
using System;

namespace SGRapidForm.Extensions
{
    public class PolicyInjectionStrategy : EnterpriseLibraryBuilderStrategy
    {
        public IUnityContainer Container
        { get; private set; }

        public PolicyInjectionStrategy(IUnityContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            this.Container = container;
        }

        public override void PreBuildUp(IBuilderContext context)
        {
            base.PreBuildUp(context);
            if (context.Policies.Get<IPolicyInjectionPolicy>(context.BuildKey) == null)
            {
                context.Policies.Set<IPolicyInjectionPolicy>(new PolicyInjectionPolicy(this.Container), context.BuildKey);
            }
        }

        public override void PostBuildUp(IBuilderContext context)
        {
            base.PostBuildUp(context);
            IPolicyInjectionPolicy policy = context.Policies.Get<IPolicyInjectionPolicy>(context.BuildKey);
            if (policy != null)
            {
                context.Existing = policy.ApplyProxy(context.Existing, BuildKey.GetType(context.OriginalBuildKey));
            }
        }
    }
}